<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            /* 
            0:初始化状态
            1:当前持有股票，且是当天买入
            2：当前持有股票，且不是当天买入
            3：当前不持有股票，且是当天卖出
            4：当前不持有股票，且是当天没卖出
            
            dp[i][j]表示当前第i天状态为j的最大利润
            */
            var maxProfit = function (prices) {
                let dp = new Array(prices.length).fill().map(() => new Array(5).fill(0))
                dp[0][1] = -prices[0]
                dp[0][2] = -prices[0]
                for (let i = 1; i < prices.length; i++) {
                    dp[i][1] = dp[i - 1][4] - prices[i]
                    dp[i][2] = Math.max(dp[i - 1][2], dp[i - 1][1])
                    dp[i][3] = Math.max(dp[i - 1][1] + prices[i], dp[i - 1][2] + prices[i])
                    dp[i][4] = Math.max(dp[i - 1][4], dp[i - 1][3])
                }
                return Math.max(dp[dp.length - 1][3], dp[dp.length - 1][4])
            }
            maxProfit([1, 2, 3, 0, 2])
        </script>
    </body>
</html>
